<template>
    <div class="user-home">
      <h2>欢迎, {{ userInfo.username }}</h2>
      <p>手机号: {{ userInfo.phoneNumber }}</p>
      <p>注册时间: {{ userInfo.createdAt }}</p>
      <p>用户状态: {{ userInfo.status }}</p>
  
      <div class="buttons">
        <button @click="openForm('send')">寄包裹</button>
        <button @click="openForm('pickup')">取包裹</button>
        <button @click="openForm('query')">查询包裹</button>
        <button @click="openForm('complaint')">投诉</button>
        <button @click="getUserInfo">刷新用户信息</button>
      </div>
  
      <!-- 表单弹窗 -->
      <div v-if="showForm" class="modal">
        <div class="modal-content">
          <span class="close" @click="closeForm">&times;</span>
          <h3>{{ formTitle }}</h3>
  
          <form v-if="currentForm === 'send'" @submit.prevent="sendParcel">
          <input v-model="parcelData.senderName" placeholder="寄件人姓名" required />
          <input v-model="parcelData.senderPhoneNumber" placeholder="寄件人手机号" required />
          <input v-model="parcelData.senderRegion" placeholder="寄件人所在地区" required />
          <input v-model="parcelData.senderDetailedAddress" placeholder="寄件人详细地址" required />

          <input v-model="parcelData.receiverName" placeholder="收件人姓名" required />
          <input v-model="parcelData.receiverPhoneNumber" placeholder="收件人手机号" required />
          <input v-model="parcelData.receiverRegion" placeholder="收件人所在地区" required />
          <input v-model="parcelData.receiverDetailedAddress" placeholder="收件人详细地址" required />

          <input v-model="parcelData.expressService" placeholder="快递服务" required />
          <input v-model="parcelData.type" placeholder="包裹类型" required />
          <input v-model.number="parcelData.weight" placeholder="包裹重量（kg）" type="number" min="0" />
          <input v-model.number="parcelData.amount" placeholder="包裹数量" type="number" min="1" required />
          <input v-model="parcelData.note" placeholder="备注" />

          <input v-model="parcelData.expectedTime" placeholder="预计送达时间" type="datetime-local" required />
          <input v-model="parcelData.paymentMethod" placeholder="支付方式" required />
          <input v-model="parcelData.status" placeholder="包裹状态" required />
          <input v-model="parcelData.location" placeholder="当前位置" />

          <button type="submit">确认寄包裹</button>
        </form>
  
          <form v-if="currentForm === 'pickup'" @submit.prevent="pickupParcel">
            <p>确认取包裹？</p>
            <button type="submit">取包裹</button>
          </form>
  
          <form v-if="currentForm === 'query'" @submit.prevent="queryParcel">
            <p>请输入查询条件：</p>
            <input v-model="queryData" placeholder="查询条件" required />
            <button type="submit">查询包裹</button>
          </form>
  
          <form v-if="currentForm === 'complaint'" @submit.prevent="fileComplaint">
            <textarea v-model="complaintText" placeholder="请输入投诉内容" required></textarea>
            <button type="submit">提交投诉</button>
          </form>
        </div>
      </div>
  
      <div v-if="message" class="message">{{ message }}</div>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  import { mapState } from 'vuex';
  
  export default {
    data() {
    return {
      message: '',
      showForm: false,
      currentForm: '',
      formTitle: '',
      queryData: '',
      complaintText: '',
      parcelData: {
        senderId: this.$store.state.info.userId,
        senderName: '',
        senderPhoneNumber: '',
        senderRegion: '',
        senderDetailedAddress: '',
        receiverName: '',
        receiverPhoneNumber: '',
        receiverRegion: '',
        receiverDetailedAddress: '',
        expressService: '',
        type: '',
        weight: 0,
        amount: 1,
        note: '',
        expectedTime: new Date().toISOString().slice(0, -8),
        paymentMethod: '',
        status: 'Pending',
        location: ''
      }
    };
  },
    computed: {
      ...mapState(['info']),
      userInfo() {
        return this.info || {};
      }
    },
    methods: {
      openForm(formType) {
        this.currentForm = formType;
        this.showForm = true;
        // 设置不同表单的标题
        this.formTitle = {
          send: '寄包裹',
          pickup: '取包裹',
          query: '查询包裹',
          complaint: '投诉'
        }[formType];
      },
      closeForm() {
        this.showForm = false;
      },
      async sendParcel() {
        try {
          const response = await axios.post('http://localhost:8080/send', this.parcelData, {
            headers: { Authorization: `Bearer ${this.$store.state.token}` }
          });
          this.message = response.data.message || '包裹寄送成功';
          this.closeForm();
        } catch (error) {
          this.message = '寄包裹失败：' + error.message;
        }
      },
      async pickupParcel() {
        try {
          const response = await axios.get(`http://localhost:8080/pickup?userId=${this.userInfo.userId}`, {
            headers: { Authorization: `Bearer ${this.$store.state.token}` }
          });
          this.message = response.data.message || '取包裹成功';
          this.closeForm();
        } catch (error) {
          this.message = '取包裹失败：' + error.message;
        }
      },
      async queryParcel() {
        try {
          const response = await axios.get(`http://localhost:8080/query?userId=${this.userInfo.userId}&query=${this.queryData}`, {
            headers: { Authorization: `Bearer ${this.$store.state.token}` }
          });
          this.message = response.data.message || '包裹查询成功';
          this.closeForm();
        } catch (error) {
          this.message = '查询包裹失败：' + error.message;
        }
      },
      async fileComplaint() {
        try {
          const response = await axios.post('http://localhost:8080/complaint', {
            userId: this.userInfo.userId,
            complaintText: this.complaintText
          }, {
            headers: { Authorization: `Bearer ${this.$store.state.token}` }
          });
          this.message = response.data.message || '投诉成功';
          this.closeForm();
        } catch (error) {
          this.message = '投诉失败：' + error.message;
        }
      },
      async getUserInfo() {
        try {
          const response = await axios.get('http://localhost:8080/info', {
            headers: { Authorization: `Bearer ${this.$store.state.token}` }
          });
          this.$store.commit('setAuth', {
            isAuthenticated: true,
            role: this.$store.state.role,
            token: this.$store.state.token,
            info: response.data
          });
          this.message = '用户信息已更新';
        } catch (error) {
          this.message = '获取用户信息失败：' + error.message;
        }
      }
    }
  };
  </script>
  
  <style scoped>
  .user-home {
    max-width: 600px;
    margin: 0 auto;
    text-align: center;
  }
  .buttons {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
    gap: 10px;
  }
  button {
    padding: 10px;
    background-color: #3498db;
    color: #fff;
    border: none;
    cursor: pointer;
    border-radius: 5px;
  }
  button:hover {
    background-color: #2980b9;
  }
  .message {
    margin-top: 20px;
    color: green;
  }
  .modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .modal-content {
    background-color: #fff;
    padding: 20px;
    border-radius: 5px;
    width: 90%;
    max-width: 500px;
    position: relative;
  }
  .close {
    position: absolute;
    top: 10px;
    right: 10px;
    cursor: pointer;
    font-size: 1.5em;
  }
  </style>
  